package cn.admobiletop.adsuyidemo.activity.ad;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;
import android.os.Handler;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;

import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import java.util.ArrayList;
import java.util.List;

import cn.admobiletop.adsuyi.ad.ADSuyiSuspendAd;
import cn.admobiletop.adsuyi.ad.data.ADSuyiAdInfo;
import cn.admobiletop.adsuyi.ad.entity.ADSuyiAdSize;
import cn.admobiletop.adsuyi.ad.entity.ADSuyiExtraParams;
import cn.admobiletop.adsuyi.ad.error.ADSuyiError;
import cn.admobiletop.adsuyi.ad.listener.ADSuyiSuspendAdListener;
import cn.admobiletop.adsuyi.util.ADSuyiDisplayUtil;
import cn.admobiletop.adsuyidemo.R;
import cn.admobiletop.adsuyidemo.adapter.TestAdapter;
import cn.admobiletop.adsuyidemo.widget.MySmartRefreshLayout;

public class SuspensionAdActivity extends AppCompatActivity {

    private MySmartRefreshLayout refreshLayout;
    private RecyclerView recyclerView;

    private FrameLayout flContainer;

    /**
     * 测试数据适配器
     */
    private TestAdapter mTestAdapter;
    /**
     * 测试数据数组
     */
    private List<Object> mTempDataList = new ArrayList<>();
    /**
     * 下拉刷新类型
     */
    private int mRefreshType;

    /**
     * 最后滑动列表时的类型
     */
    private int mLastScrollState = RecyclerView.SCROLL_STATE_IDLE;
    /**
     * 当前使用的信息流广告
     */
    private ADSuyiSuspendAd mADSuyiSuspendAd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_suspension_ad);

        initView();
        initAdapter();
        initListener();

        loadSuspensionAd();
    }

    private void initView() {
        recyclerView = findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        refreshLayout = findViewById(R.id.refreshLayout);

        flContainer = findViewById(R.id.flContainer);
    }

    private void initAdapter() {
        mTestAdapter = new TestAdapter();
        recyclerView.setAdapter(mTestAdapter);
    }

    private void initListener() {
        // 下拉刷新上拉加载监听
        if (refreshLayout != null) {
            refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
                @Override
                public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                    mRefreshType = MySmartRefreshLayout.TYPE_LOAD_MORE;
                    loadData();
                }

                @Override
                public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                    mRefreshType = MySmartRefreshLayout.TYPE_FRESH;
                    if (mTestAdapter != null) {
                        mTestAdapter.clearData();
                    }
                    loadData();
                }
            });
            refreshLayout.autoRefresh();
        }

        // 布局滑动监听
        if (recyclerView != null) {
            recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
                @Override
                public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                    super.onScrollStateChanged(recyclerView, newState);
                    if (mLastScrollState == RecyclerView.SCROLL_STATE_IDLE &&
                            (newState == RecyclerView.SCROLL_STATE_DRAGGING ||
                                    newState == RecyclerView.SCROLL_STATE_SETTLING)) {
                        // 从静止状态变为滚动状态：滚动开始
                        setRlSuspensionAdRightMargin(-ADSuyiDisplayUtil.dp2px(58));
                        setRlSuspensionAdAlpha(0.5f);
                    } else if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                        // 滚动停止
                        setRlSuspensionAdRightMargin(ADSuyiDisplayUtil.dp2px(16));
                        setRlSuspensionAdAlpha(1.0f);
                    }
                    // 更新状态
                    mLastScrollState = newState;
                }
            });
        }
    }

    /**
     * 加载测试数据
     */
    private void loadData() {
        mTempDataList.clear();
        for (int i = 0; i < 20; i++) {
            mTempDataList.add("模拟的普通数据 : " + (mTestAdapter == null ? 0 : mTestAdapter.getItemCount() + i));
        }
        if (mTestAdapter != null) {
            mTestAdapter.addData(mTempDataList);
        }
        new Handler(getMainLooper()).postDelayed(new Runnable() {
            @Override
            public void run() {
                if (refreshLayout != null) {
                    refreshLayout.finish(mRefreshType, true, false);
                }
            }
        }, 500);
    }

    /**
     * 加载悬浮广告
     */
    public void loadSuspensionAd() {
        mADSuyiSuspendAd = new ADSuyiSuspendAd(this, flContainer);
        // 传入广告布局图片宽高60（单位：dp）
        mADSuyiSuspendAd.setLocalExtraParams(
            new ADSuyiExtraParams.Builder().adSize(
                new ADSuyiAdSize(
                        ADSuyiDisplayUtil.dp2px(60),
                        ADSuyiDisplayUtil.dp2px(60)
                )
            ).build()
        );
        mADSuyiSuspendAd.setAutoRefreshInterval(30);
        mADSuyiSuspendAd.setListener(new ADSuyiSuspendAdListener() {
            @Override
            public void onAdReceive(ADSuyiAdInfo adSuyiAdInfo) {

            }

            @Override
            public void onAdExpose(ADSuyiAdInfo adSuyiAdInfo) {

            }

            @Override
            public void onAdClick(ADSuyiAdInfo adSuyiAdInfo) {

            }

            @Override
            public void onAdClose(ADSuyiAdInfo adSuyiAdInfo) {
                if (flContainer != null) {
                    flContainer.removeAllViews();
                }
                if (mADSuyiSuspendAd != null) {
                    mADSuyiSuspendAd.release();
                }
            }

            @Override
            public void onAdFailed(ADSuyiError adSuyiError) {

            }
        });
        // 上线需要替换成自己的
        mADSuyiSuspendAd.loadAd("c078638e143ac16f46");
    }

    /**
     * 设置广告布局右边距
     * 滑动布局时可以将悬浮广告偏移
     * @param rightMarginPx
     */
    public void setRlSuspensionAdRightMargin(int rightMarginPx) {
        if (flContainer != null) {
            RelativeLayout.LayoutParams suspensionAdParams = (RelativeLayout.LayoutParams) flContainer.getLayoutParams();
            suspensionAdParams.rightMargin = rightMarginPx;
            flContainer.setLayoutParams(suspensionAdParams);
        }
    }

    /**
     * 设置广告布局透明度
     * 滑动布局时可以将悬浮广告透明度降低
     * @param alpha
     */
    public void setRlSuspensionAdAlpha(float alpha) {
        if (flContainer != null) {
            flContainer.setAlpha(alpha);
        }
    }
}